package com.mf.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mf.basic.BasicDuration;
import com.mf.basic.BasicKey;
import com.mf.entity.request.PagingRequest;
import com.mf.entity.request.search.UserPageListSearch;
import com.mf.entity.request.user.CheckedCodeRequest;
import com.mf.entity.request.user.*;
import com.mf.entity.vo.UserVo;
import com.mf.enums.SendCodeEnum;
import com.mf.feigin.AuthCodeFeignService;
import com.mf.interceptor.UserTokenInterceptor;
import com.mf.result.Result;
import com.mf.result.ResultCodeEnum;
import com.mf.service.IUserService;
import com.mf.utils.JWTUtil;
import com.mf.utils.RedisOperator;
import com.mf.utils.VerifyUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;


/**
 * @author mf
 * @since 2024-07-18
 */
@RestController
@RequestMapping("api/user/v1")
@Tag(name = "用户模块")
public class UserController {
    @Resource
    private RedisOperator redisOperator;

    @Resource
    private IUserService userService;

    @Resource
    private AuthCodeFeignService authCodeFeignService;

    @Operation(summary = "分页查询用户")
    @PostMapping("pageUserList")
    public Result<Page<UserVo>> pageUserList(@RequestBody UserPageListSearch userPageListSearch) {
        return Result.success(userService.pageList(userPageListSearch));
    }

    @Operation(summary = "修改用户状态")
    @GetMapping("changeStatusByUser")
    public Result<Integer> changeStatusByUser(@RequestParam("status") Integer status, @RequestParam("id") Long id) {
        return Result.success(userService.changeStatusByUser(status, id));
    }

    @Operation(summary = "删除用户")
    @GetMapping("deleteById")
    public Result<Boolean> deleteById(@RequestParam("id") Long id) {
        return Result.success(userService.removeById(id));
    }
    
    @Operation(summary = "用户修改密码")
    @PostMapping("userChangePwd")
    public Result<Integer> userChangePwd(@Valid @RequestBody UserChangePwdRequest userChangePwdRequest) {
        return Result.success(userService.userChangePwd(userChangePwdRequest));
    }

    @Operation(summary = "管理员修改用户账户密码")
    @PostMapping("adminChangeUserPwd")
    public Result<Integer> adminChangeUserPwd(@Valid @RequestBody AdminChangeUserPwdRequest adminChangeUserPwdRequest) {
        return Result.success(userService.adminChangeUserPwd(adminChangeUserPwdRequest));
    }

    @Operation(summary = "用户登录")
    @PostMapping("login")
    public Result<UserTokenRequest> login(@Valid @RequestBody UserLoginRequest userLoginRequest) {
        return Result.success(userService.login(userLoginRequest));
    }

    @Operation(summary = "用户注册")
    @PostMapping("register")
    public Result<String> register(@Valid @RequestBody UserRegisterRequest userRegisterRequest,HttpServletRequest request) {
        String captchaKey = BasicKey.getCaptchaKey(request,SendCodeEnum.REGISTER.value);
        // 验证验证码
        CheckedCodeRequest checkedCodeRequest = CheckedCodeRequest.builder()
                .captchaCode(userRegisterRequest.getCaptcha())
                .captchaKey(captchaKey)
                .type(SendCodeEnum.REGISTER.value).build();
        Boolean flag = authCodeFeignService.checkedCode(checkedCodeRequest);
        if(flag){
            userService.register(userRegisterRequest);
            // 删除验证码
            authCodeFeignService.deleteCode(SendCodeEnum.REGISTER.value);
            return Result.success();
        }
        return Result.fail("验证码错误");
    }

    @Operation(summary = "编辑用户")
    @PostMapping("edit")
    public Result<Void> edit(@RequestBody UserVo userVo) {
        return Result.success(userService.edit(userVo));
    }

    /**
     * 根据刷新token更新token
     */
    @Operation(summary = "根据刷新token更新token")
    @PostMapping("refreshToken")
    public Result<String> refreshToken(@Valid @RequestParam("key") String refreshToken,
                                       HttpServletRequest request) {

        String token = request.getHeader("Token");
        UserVo userVo1 = UserTokenInterceptor.checkToken(token);

        // 验证刷新token 是否过期
        String uToken = redisOperator.get(BasicKey.REDIS_USER_REFRESH_TOKEN + userVo1.getNameAndId());

        if (VerifyUtils.isEmpty(uToken)) {
            return Result.fail(ResultCodeEnum.REFRESH_TOKEN_EXPIRED);
        }

        String[] splitToken = uToken.split(":");

        // 验证刷新token和token是否有被修改
        if (splitToken.length != 2 || !splitToken[0].equals(refreshToken) || !splitToken[1].equals(token)) {
            return Result.fail(ResultCodeEnum.REFRESH_TOKEN_EXPIRED);
        }

        UserVo userVo = JWTUtil.checkJwt(token);
        if (userVo != null) {

            // 重新设置刷新JWT的过期时间
            redisOperator.set(BasicKey.REDIS_USER_TOKEN + userVo.getNameAndId(),
                    token, BasicDuration.TOKEN_DURATION);
            // 刷新 刷新token时间
            redisOperator.expire(BasicKey.REDIS_USER_REFRESH_TOKEN + userVo.getNameAndId(),
                    BasicDuration.REFRESH_TOKEN_DURATION);

            // 返回当前有效的JWT或相关消息（取决于你的应用程序需求）
            return Result.success(); // 或者返回新的JWT，如果适用
        }
        // JWT验证失败
        return Result.fail(ResultCodeEnum.LOGIN_EXPIRED); // 或者其他更具体的错误枚举
    }

}
